import 'package:flutter/material.dart';
import 'package:refresh_page/refresh_page.dart';
import 'package:get/get.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      builder: RefreshPageConfiguration.init(
        emptyBuilder: (context, controller) => const Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.inbox_outlined, size: 60, color: Colors.grey),
              SizedBox(height: 16),
              Text('暂无数据', style: TextStyle(color: Colors.grey)),
            ],
          ),
        ),
        errorBuilder: (context, controller, reload) => Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.error_outline, size: 60, color: Colors.redAccent),
              SizedBox(height: 16),
              Text('加载失败', style: TextStyle(color: Colors.grey)),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: reload,
                child: const Text('重新加载'),
              ),
            ],
          ),
        ),
        loadingBuilder: (context, controller) => const Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 16),
              Text('加载中...', style: TextStyle(color: Colors.grey)),
            ],
          ),
        ),
        header: const WaterDropHeader(),
        footer: const ClassicFooter(
          loadingText: '加载中...',
          canLoadingText: '释放加载更多',
          idleText: '上拉加载更多',
          noDataText: '没有更多数据了',
        ),
      ),
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

// 模拟数据项
class ItemData {
  final int id;
  final String title;
  final String description;

  ItemData({required this.id, required this.title, required this.description});
}

// 控制器
class TestController extends RefreshPageController<ItemData> {
  TestController({String? tag}) : super();

  @override
  Future<RefreshPageResult<ItemData>> request(int page) async {
    // 模拟网络延迟
    await Future.delayed(const Duration(seconds: 2));

    // 模拟随机错误
    if (page > 1 && DateTime.now().millisecondsSinceEpoch % 10 == 0) {
      return RefreshPageResult.error('网络错误');
    }

    // 模拟数据
    final items = List.generate(
      10,
      (index) => ItemData(
        id: (page - 1) * 10 + index + 1,
        title: '标题 ${(page - 1) * 10 + index + 1}',
        description: '这是第 ${(page - 1) * 10 + index + 1} 个项目的详细描述',
      ),
    );

    // 模拟空数据
    if (page == 1 && DateTime.now().millisecondsSinceEpoch % 7 == 0) {
      return RefreshPageResult.success([]);
    }

    // 模拟没有更多数据
    final isLastPage = page >= 3;

    return RefreshPageResult.success(items, over: isLastPage);
  }
}

// 主页
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    // 注册控制器，使用 tag 区分
    final listTag = 'list_controller';
    Get.put(TestController(tag: listTag), tag: listTag);

    return Scaffold(
      appBar: AppBar(
        title: const Text('刷新页面示例'),
        actions: [
          IconButton(
            icon: const Icon(Icons.grid_view),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const GridPage()),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.person),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const CustomPositionPage()),
            ),
          ),
        ],
      ),
      body: RefreshList<ItemData, TestController>(
        tag: listTag,
        items: Get.find<TestController>(tag: listTag).data,
        itemBuilder: (item, index) => ListTile(
          leading: CircleAvatar(child: Text('${item.id}')),
          title: Text(item.title),
          subtitle: Text(item.description),
          onTap: () {},
        ),
        // 自定义分隔线
        separatorBuilder: (_, __) => const Divider(height: 1),
      ),
    );
  }
}

// 网格页面示例
class GridPage extends StatelessWidget {
  const GridPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 为网格页面创建独立的控制器
    final gridTag = 'grid_controller';
    Get.put(TestController(tag: gridTag), tag: gridTag);

    return Scaffold(
      appBar: AppBar(
        title: const Text('网格视图示例'),
      ),
      body: RefreshGrid<ItemData, TestController>(
        tag: gridTag,
        items: Get.find<TestController>(tag: gridTag).data,
        crossAxisCount: 2,
        childAspectRatio: 0.8,
        itemBuilder: (item, index) => Card(
          elevation: 2,
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AspectRatio(
                  aspectRatio: 16 / 9,
                  child: Container(
                    color: Colors.blue.withOpacity(0.2),
                    alignment: Alignment.center,
                    child: Text(
                      '${item.id}',
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  item.title,
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  item.description,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 自定义位置示例页面
class CustomPositionPage extends StatelessWidget {
  const CustomPositionPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 为自定义位置页面创建独立的控制器
    final customTag = 'custom_controller';
    Get.put(TestController(tag: customTag), tag: customTag);

    return Scaffold(
      body: RefreshPage<TestController>(
        tag: customTag,
        emptyOverlay: false,
        errorOverlay: false,
        statePositionBuilder: (stateWidget) {
          return CustomScrollView(
            slivers: [
              // 可折叠的顶部栏
              SliverAppBar(
                expandedHeight: 200.0,
                floating: false,
                pinned: true,
                flexibleSpace: FlexibleSpaceBar(
                  title: const Text('用户中心'),
                  background: Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [Colors.blue, Colors.purple],
                      ),
                    ),
                    child: Stack(
                      children: [
                        Positioned(
                          bottom: 60,
                          left: 16,
                          child: Row(
                            children: [
                              const CircleAvatar(
                                radius: 30,
                                backgroundImage: NetworkImage(
                                  'https://via.placeholder.com/150',
                                ),
                              ),
                              const SizedBox(width: 16),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '用户名称',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    'ID: 12345678',
                                    style: TextStyle(
                                      color: Colors.white.withOpacity(0.8),
                                      fontSize: 14,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // 用户统计信息
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Card(
                    elevation: 2,
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _buildStatItem('关注', '128'),
                          _buildStatItem('粉丝', '256'),
                          _buildStatItem('获赞', '1024'),
                        ],
                      ),
                    ),
                  ),
                ),
              ),

              // 标签栏
              SliverPersistentHeader(
                pinned: true,
                delegate: _SliverTabBarDelegate(
                  TabBar(
                    tabs: const [
                      Tab(text: '动态'),
                      Tab(text: '收藏'),
                      Tab(text: '点赞'),
                    ],
                    labelColor: Theme.of(context).primaryColor,
                    unselectedLabelColor: Colors.grey,
                    indicatorColor: Theme.of(context).primaryColor,
                  ),
                ),
              ),

              // 状态显示区域 (空状态、错误状态等)
              SliverToBoxAdapter(
                child: SizedBox(
                  height: 300, // 给状态显示区域一个固定高度
                  child: stateWidget,
                ),
              ),

              // 内容区域
              SliverPadding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                sliver: GetBuilder<TestController>(
                  tag: customTag,
                  builder: (controller) {
                    if (controller.loadState.value != LoadState.success) {
                      return const SliverToBoxAdapter(child: SizedBox());
                    }

                    return SliverList(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) {
                          final item = controller.data[index];
                          return _buildDynamicItem(item);
                        },
                        childCount: controller.data.length,
                      ),
                    );
                  },
                ),
              ),

              // 底部间距
              const SliverToBoxAdapter(
                child: SizedBox(height: 20),
              ),
            ],
          );
        },
        childBuilder: (controller) {
          return CustomScrollView(
            slivers: [
              // 可折叠的顶部栏
              SliverAppBar(
                expandedHeight: 200.0,
                floating: false,
                pinned: true,
                flexibleSpace: FlexibleSpaceBar(
                  title: const Text('用户中心'),
                  background: Container(
                    decoration: const BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [Colors.blue, Colors.purple],
                      ),
                    ),
                    child: Stack(
                      children: [
                        Positioned(
                          bottom: 60,
                          left: 16,
                          child: Row(
                            children: [
                              const CircleAvatar(
                                radius: 30,
                                backgroundImage: NetworkImage(
                                  'https://via.placeholder.com/150',
                                ),
                              ),
                              const SizedBox(width: 16),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Text(
                                    '用户名称',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  const SizedBox(height: 4),
                                  Text(
                                    'ID: 12345678',
                                    style: TextStyle(
                                      color: Colors.white.withOpacity(0.8),
                                      fontSize: 14,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),

              // 用户统计信息
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Card(
                    elevation: 2,
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _buildStatItem('关注', '128'),
                          _buildStatItem('粉丝', '256'),
                          _buildStatItem('获赞', '1024'),
                        ],
                      ),
                    ),
                  ),
                ),
              ),

              // 标签栏
              SliverPersistentHeader(
                pinned: true,
                delegate: _SliverTabBarDelegate(
                  TabBar(
                    tabs: const [
                      Tab(text: '动态'),
                      Tab(text: '收藏'),
                      Tab(text: '点赞'),
                    ],
                    labelColor: Theme.of(context).primaryColor,
                    unselectedLabelColor: Colors.grey,
                    indicatorColor: Theme.of(context).primaryColor,
                  ),
                ),
              ),

              // 内容列表
              SliverPadding(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                sliver: SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (context, index) {
                      final item = controller.data[index];
                      return _buildDynamicItem(item);
                    },
                    childCount: controller.data.length,
                  ),
                ),
              ),

              // 底部间距
              const SliverToBoxAdapter(
                child: SizedBox(height: 20),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildStatItem(String title, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          title,
          style: TextStyle(
            fontSize: 14,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildDynamicItem(ItemData item) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16.0),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息和时间
            Row(
              children: [
                const CircleAvatar(
                  radius: 18,
                  backgroundImage:
                      NetworkImage('https://via.placeholder.com/150'),
                ),
                const SizedBox(width: 12),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '用户名称',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '2小时前',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.more_horiz),
                  onPressed: () {},
                ),
              ],
            ),

            // 内容
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 12.0),
              child: Text(
                '${item.title} - ${item.description}',
                style: const TextStyle(fontSize: 16),
              ),
            ),

            // 图片内容
            if (item.id % 3 == 0)
              Container(
                height: 200,
                margin: const EdgeInsets.only(bottom: 12.0),
                decoration: BoxDecoration(
                  color: Colors.grey[300],
                  borderRadius: BorderRadius.circular(8),
                  image: const DecorationImage(
                    image: NetworkImage('https://via.placeholder.com/800x400'),
                    fit: BoxFit.cover,
                  ),
                ),
              ),

            // 互动按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildActionButton(
                    Icons.thumb_up_outlined, '${(item.id * 7) % 100}'),
                _buildActionButton(
                    Icons.chat_bubble_outline, '${(item.id * 3) % 50}'),
                _buildActionButton(Icons.share_outlined, '${item.id % 20}'),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButton(IconData icon, String count) {
    return Row(
      children: [
        Icon(icon, size: 18, color: Colors.grey[600]),
        const SizedBox(width: 4),
        Text(
          count,
          style: TextStyle(
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }
}

// 用于实现固定的TabBar的代理类
class _SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar tabBar;

  _SliverTabBarDelegate(this.tabBar);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Theme.of(context).scaffoldBackgroundColor,
      child: tabBar,
    );
  }

  @override
  double get maxExtent => tabBar.preferredSize.height;

  @override
  double get minExtent => tabBar.preferredSize.height;

  @override
  bool shouldRebuild(covariant _SliverTabBarDelegate oldDelegate) {
    return tabBar != oldDelegate.tabBar;
  }
}
